
package com.probiz.estore.content.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.content.TemplateFileFilter;
import com.probiz.estore.common.model.content.TemplateInfo;
import com.probiz.estore.common.util.FileUtil;
import com.probiz.estore.content.service.TemplateManager;
import com.probiz.estore.core.exception.ApplicationException;

/**
 * Manager implementation for Template, responsible for business processing, and
 * communicate between web and persistence layer.
 */
public class TemplateManagerImpl implements TemplateManager {

	protected final transient Log	logger	= LogFactory.getLog(getClass());
	
	public void deleteTemplate(String templatePath) {
		if (StringUtils.isEmpty(templatePath)) {
			throw new ApplicationException("templatePath is required.", null);
		}
		TemplateInfo templateInfo = new TemplateInfo();
		templateInfo.setTemplatePath(templatePath);
		String filePath = getFullTemplatePath(templateInfo);
		File file = new File(filePath);
		if (file.exists()) {
			logger.info("deleting template:" + filePath);
			file.delete();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.content.service.TemplateManager#editTemplateContent(java.lang.String)
	 */
	public TemplateInfo editTemplateContent(String templatePath) {
		if (StringUtils.isEmpty(templatePath)) {
			throw new ApplicationException("templatePath is required.", null);
		}
		TemplateInfo templateInfo = new TemplateInfo();
		templateInfo.setTemplatePath(templatePath);
		String filePath = getFullTemplatePath(templateInfo);
		logger.debug("reading template for edit:" + filePath);
		File file = new File(filePath);
		if (file.exists()) {
			logger.debug("template file found:" + filePath);
			templateInfo = getTemplateInfoFromFile(file);
			if (!file.isDirectory()) {
				try {
					templateInfo.setTemplateContent(FileUtil
							.readFileToString(file.getAbsolutePath()));
				} catch (IOException e) {
					throw new ApplicationException(
							"Read template content error.", e);
				}
			}
		}
		return templateInfo;
	}

	public String getFullTemplatePath(TemplateInfo templateInfo) {
		return new StringBuilder(ConfigUtil.getInstance()
				.getStoreFrontInstallationPath()).append(
				templateInfo.getTemplatePath()).toString();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.content.service.TemplateManager#getPageTemplates()
	 */
	public List<TemplateInfo> getPageTemplates() {
		return getTemplateTreeList("jsp");
	}

	private TemplateInfo getTemplateInfoFromFile(File file) {
		TemplateInfo templInfo = new TemplateInfo();
		templInfo.setFileName(file.getName());
		templInfo.setTemplatePath(getTemplatePathFromFile(file));
		templInfo.setIsDirectory(file.isDirectory());
		templInfo.setLevel(FileUtil.countDirectoryLevel(templInfo.getTemplatePath()) - 1);
		templInfo.setTemplateName(null);
		templInfo.setTemplateType(null);
		return templInfo;
	}

	private String getTemplatePathFromFile(File templateFile) {
		return FileUtil.formatPath(templateFile.getPath()).substring(
				ConfigUtil.getInstance().getStoreFrontInstallationPath()
						.length());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.content.service.TemplateManager#getTemplateTree(java.lang.Short)
	 */
	public List<TemplateInfo> getTemplateTreeList(String templateType) {

		StringBuilder sb = new StringBuilder(ConfigUtil.getInstance()
				.getStoreFrontInstallationPath()).append("/");
		//sb.append(templateType.indexOf("jsp") == 0 ? "pages" : templateType);
		//for v3.5 mfr
		sb.append(templateType.indexOf("jsp") == 0 ? "themes/default/pages" : templateType);

		File templateCategoryDirectory = new File(sb.toString());

		List<File> templateFileTreeList = FileUtil.listFiles(
				new ArrayList<File>(), templateCategoryDirectory,
				new TemplateFileFilter(templateType));

		// 根据文件列表生成所需的模版信息列表（树）
		List<TemplateInfo> templateTreeList = new ArrayList<TemplateInfo>();
		for (Iterator<File> iter = templateFileTreeList.iterator(); iter
				.hasNext();) {
			templateTreeList.add(getTemplateInfoFromFile(iter.next()));
		}

		return templateTreeList;
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.content.service.TemplateManager#saveTemplate(com.probiz.estore.common.model.content.TemplateInfo)
	 */
	public void saveTemplateContent(TemplateInfo templateInfo) {
		if (templateInfo.getIsDirectory()) {
			templateInfo.setTemplatePath(templateInfo.getTemplatePath() + "/"
					+ templateInfo.getFileName() + "."
					+ templateInfo.getTemplateType());
		}

		try {
			FileUtil.writeStringToFile(getFullTemplatePath(templateInfo),
					templateInfo.getTemplateContent());
		} catch (IOException e) {
			throw new ApplicationException("Save template content error.", e);
		}

	}

}
